# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

from pylons import request
from pylons.i18n import lazy_ugettext as _
from webhelpers.html import tags, literal
from webhelpers.html.builder import HTML
from babel import dates

from chowa.model.site import Option, UserOption
from chowa.lib.base import Session
from chowa.lib.helpers import select_bool, select_month

def get_option(name):
    try:
        option = Session.query(Option).filter_by(name=name).one()
        value = option.value
        if option.type == 'boolean': value=bool(int(value))
        if option.type in ['integer', 'month']: value=int(value)
        return value
    except:
        return

def get_personal_option(name):
    identity = request.environ.get('repoze.who.identity')
    if identity:
        user = identity.get('user')
        try:
            personal = Session.query(UserOption).join(Option) \
                .filter(Option.name == name) \
                .filter(UserOption.user_id == user.id).one()
            value = personal.value
            if personal.option.type == 'boolean': value=bool(int(value))
            if personal.option.type in ['integer', 'month']: value=int(value)
            return value
        except:
            return

def set_option(name, value):
    try:
        option = Session.query(Option).filter_by(name=name).one()
    except:
        option = Option(name=name)
    option.value = value
    Session.add(option)
    Session.commit()

def set_personal_option(name, value):
    identity = request.environ.get('repoze.who.identity')
    if identity:
        user = identity.get('user')
        try:
            option = Option(name=name, type='text')
            Session.add(option)
            Session.commit()
        except:
            Session.rollback()
            option = Session.query(Option).filter_by(name=name).one()
        try:
            user_option = UserOption(option=option, user=user, value=unicode(value))
            Session.add(user_option)
            Session.commit()
        except:
            Session.rollback()
            user_option = Session.query(UserOption).filter_by(option=option, user=user).one()
            user_option.value = unicode(value)
            Session.commit()
            

def add_options(options, session, prefix=''):
    for option in options:
        name, type, verbose, default = option
        name = prefix + '.' + name
        query = session.query(Option).filter_by(name=name)
        if not query.count():
            db_option = Option(name=name,
                               type=type,
                               verbose=verbose,
                               value=default,
                               default=default)
            session.add(db_option)
    session.commit()


class GeneralOption(object):
    def __init__(self, name=None, value=None, verbose=None):
        self.name = name
        self.value = value
        self.verbose = verbose

class TextOption(GeneralOption):
    def render(self):
        return tags.text(self.name, value=self.value)

class IntegerOption(GeneralOption):
    def render(self):
        return tags.text(self.name, value=self.value)

class FloatOption(GeneralOption):
    def render(self):
        return tags.text(self.name, value=self.value)

class BooleanOption(GeneralOption):
    def render(self):
        return select_bool(self.name, self.value)

class MonthOption(GeneralOption):
    def render(self):
        return select_month(self.name, self.value)

TYPES = {
    'text': TextOption,
    'integer': IntegerOption,
    'float': FloatOption,
    'boolean': BooleanOption,
    'month': MonthOption,
}

class GroupOption(GeneralOption):
    def render(self):
        options = Session.query(Option).filter(Option.name.like(self.name + '.%')).all()
        options = [TYPES[option.type](option.name, option.value, option.verbose) for option in options]
        
        cols = len(options)
        col_width = 100.0 / cols
        style='width:%s%%' % col_width
        
        tds = literal()
        for option in options:
            tds += HTML.tag('th', c=HTML.tag('label', for_=option.name, c=option.verbose)+':')
            tds += HTML.tag('td', c=option.render(), style=style)
        tr = HTML.tag('tr', c=tds)
        table = HTML.tag('table', class_='form-table', c=tr)
        return HTML.tag('fieldset', c=table)

TYPES['group'] = GroupOption


class OptionsFieldSet(object):
    def __init__(self, options=[]):
        self.options = options
        
    def append(self, option):
        self.options += option
        
    def render(self):
        query = Session.query(Option)
        options = query.filter(Option.name.in_(self.options)).all()
        options = [TYPES[option.type](option.name, option.value, option.verbose) for option in options]
        trs = literal()
        for option in options:
            caption = HTML.tag('th', c=HTML.tag('label', for_=option.name, c=option.verbose)+':')
            field = HTML.tag('td', c=option.render())
            trs += HTML.tag('tr', c=caption+field+'\n')
        html = HTML.tag('table', class_='form-table', c=trs)
        return html
    
    def save(self, data):
        query = Session.query(Option)
        for option in data:
            option_query = query.filter_by(name=option)
            if option_query.count() == 1:
                option_record = option_query.one()
                option_record.value = data[option]
                Session.add(option_record)
        Session.commit()
